#include <iostream>
#include "DynamicArray.h"
using namespace std;

DynamicArray::DynamicArray(int capacity):m_size(0), m_capacity(capacity)
{
    if (capacity <= 0)      //capacity为非正数
    {
        capacity = 10;
    }
    m_data = new ElementType[m_capacity];
}

DynamicArray::DynamicArray(const DynamicArray &a)
{
    m_size = a.m_size;
    m_capacity = a.m_capacity;
    m_data = new ElementType[m_capacity];
    for (int idx = 0; idx < m_size; idx++)
    {
        m_data[idx] = a.m_data[idx];
    }
}

DynamicArray::~DynamicArray()
{
    delete []m_data;
}

void DynamicArray::show(void (*printFunc)(ElementType arg))
{
    for (int idx = 0; idx < m_size; idx++)
    {
        printFunc(m_data[idx]);
    }
    cout << endl;
}

void DynamicArray::expandCapacity(int capacity)
{
    m_capacity = capacity;
    ElementType *newP = new ElementType[m_capacity];
    for (int idx = 0; idx < m_size; idx++)
    {
        newP[idx] = m_data[idx];
    }
    delete []m_data;
    m_data = newP;
}

void DynamicArray::shrinkCapacity(int capacity)
{
    m_capacity = capacity;
    ElementType *newP = new ElementType[m_capacity];
    for (int idx = 0; idx < m_size; idx++)
    {
        newP[idx] = m_data[idx];
    }
    delete []m_data;
    m_data = newP;
}

void DynamicArray::InsertTail(ElementType data)
{
    if (m_size == m_capacity)
    {
        expandCapacity(m_capacity * 2);
    }
    m_data[m_size] = data;
    m_size++;
}

void DynamicArray::InsertAppointPos(int index, ElementType data)
{
    if (index < 0 || index > m_size)
    {
        cout << "index error" << endl;
        return;
    }
    if (m_size == m_capacity)
    {
        expandCapacity(m_capacity * 2);
    }
    for (int idx = m_size; idx > index; idx--)
    {
        m_data[idx] = m_data[idx - 1];
    }
    m_data[index] = data;
    m_size++;
}

void DynamicArray::RemoveTail()
{
    if (m_size < (m_capacity >> 1))
    {
        shrinkCapacity(m_capacity >> 1);
    }
    m_data[m_size - 1] = m_data[m_size];
    m_size--;
}

void DynamicArray::RemoveAppointPos(int index)
{
    if (index < 0 || index >= m_size)
    {
        cout << "index error" << endl;
        return;
    }
    if (m_size < (m_capacity >> 1))
    {
        shrinkCapacity(m_capacity >> 1);
    }
    for (int idx = index; idx < m_size - 1; idx++)
    {
        m_data[idx] = m_data[idx + 1];
    }
    m_size--;
}

void DynamicArray::RemoveAppointElement(ElementType data, int (*strcmpFunc)(ElementType arg1, ElementType arg2))
{
    if (m_size < (m_capacity >> 1))
    {
        shrinkCapacity(m_capacity >> 1);
    }
    for (int idx = 0; idx < m_size; idx++)
    {
        int ret = strcmpFunc(m_data[idx], data);
        if (ret == 0)
        {
            RemoveAppointPos(idx);
            idx--;
        }
    }
}